package com.fulihui.wgj.admin.integration.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fulihui.common.builder.web.JsonResultBuilder;
import com.fulihui.common.builder.web.PageViewBuilder;
import com.fulihui.common.enums.MaterialTypeEnum;
import com.fulihui.common.result.rpc.BaseResult;
import com.fulihui.common.result.rpc.SimpleResult;
import com.fulihui.common.result.web.PageView;
import com.fulihui.common.result.web.Result;
import com.fulihui.common.util.DateUtils;
import com.fulihui.common.util.RpcResultCheckUtil;
import com.fulihui.wgj.admin.api.material.request.MaterialPageRequest;
import com.fulihui.wgj.admin.api.material.vo.MaterialImageVO;
import com.fulihui.wgj.admin.api.material.vo.MaterialNewsItemVO;
import com.fulihui.wgj.admin.api.material.vo.MaterialNewsVO;
import com.fulihui.wgj.admin.config.properties.AdminProperties;
import com.fulihui.wgj.admin.integration.MaterialServiceClient;
import com.fulihui.wgj.facade.dto.WxMaterialDTO;
import com.fulihui.wgj.facade.request.material.WxMaterialPageQueryRequest;
import com.fulihui.wgj.facade.request.material.WxMaterialRequest;
import com.fulihui.wgj.facade.request.material.WxMaterialSyncRequest;
import com.fulihui.wgj.facade.result.material.WxMaterialPageResult;
import com.fulihui.wgj.facade.service.material.WxMaterialService;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Iterator;
import java.util.List;

/**
 * @author: Levon
 * @date: 2018-07-11 15:32
 */
@Service
public class MaterialServiceClientImpl implements MaterialServiceClient {

    private static final Logger LOGGER = LoggerFactory.getLogger(MaterialServiceClientImpl.class);

    @Reference(version = "1.0.0")
    WxMaterialService wxMaterialService;

    @Autowired
    AdminProperties adminProperties;

    /**
     * 分页查询图文列表
     *
     * @param request
     * @return
     */
    @Override
    public PageView<MaterialNewsVO> queryNewsPage(MaterialPageRequest request) {

        WxMaterialPageQueryRequest pageQueryRequest = new WxMaterialPageQueryRequest();
        pageQueryRequest.setAppId(request.getAppId());
        pageQueryRequest.setType(MaterialTypeEnum.news.getCode());
        pageQueryRequest.setPage(request.getPage());
        pageQueryRequest.setRows(request.getRows());

        List<MaterialNewsVO> materialNewsVOs = Lists.newArrayList();

        WxMaterialPageResult pageResult = wxMaterialService.pageQueryWxMaterialByType(pageQueryRequest);
        if (RpcResultCheckUtil.isSuccess(pageResult)) {
            List<WxMaterialDTO> values = pageResult.getValue();
            if (!CollectionUtils.isEmpty(values)) {
                for (WxMaterialDTO material : values) {
                    if (StringUtils.isEmpty(material.getContent())) {
                        continue;
                    }
                    MaterialNewsVO materialNewsVO = new MaterialNewsVO();
                    materialNewsVO.setItems(parse(material.getContent()));
                    materialNewsVO.setUpdateTime(DateUtils.format(material.getUpdateTime(), DateUtils.noSecondFormat));
                    materialNewsVO.setMediaId(material.getMediaId());
                    materialNewsVOs.add(materialNewsVO);
                }
            }
        }
        return PageViewBuilder.build(materialNewsVOs, pageResult.getPage(), pageResult.getRows(), pageResult.getTotalRows());
    }

    /**
     * 分页查询图片列表
     *
     * @param request
     * @return
     */
    @Override
    public PageView<MaterialImageVO> queryImagePage(MaterialPageRequest request) {

        WxMaterialPageQueryRequest pageQueryRequest = new WxMaterialPageQueryRequest();
        pageQueryRequest.setAppId(request.getAppId());
        pageQueryRequest.setType(MaterialTypeEnum.image.getCode());
        pageQueryRequest.setPage(request.getPage());
        pageQueryRequest.setRows(request.getRows());

        List<MaterialImageVO> imageVOS = Lists.newArrayList();

        WxMaterialPageResult pageResult = wxMaterialService.pageQueryWxMaterialByType(pageQueryRequest);
        if (RpcResultCheckUtil.isSuccess(pageResult)) {
            List<WxMaterialDTO> values = pageResult.getValue();
            if (!CollectionUtils.isEmpty(values)) {
                for (WxMaterialDTO material : values) {
                    MaterialImageVO imageVO = new MaterialImageVO();
                    imageVO.setImgUrl(material.getImageUrl());
                    imageVO.setMediaId(material.getMediaId());
                    imageVO.setUpdateTime(DateUtils.format(material.getUpdateTime(), DateUtils.noSecondFormat));
                    imageVOS.add(imageVO);
                }
            }
        }
        return PageViewBuilder.build(imageVOS, pageResult.getPage(), pageResult.getRows(), pageResult.getTotalRows());
    }

    /**
     * 解析图文
     *
     * @param content
     * @return
     */
    @Override
    public List<MaterialNewsItemVO> parse(String content) {
        List<MaterialNewsItemVO> materialNewsVOs = Lists.newArrayList();
        JSONObject jsonObject = JSON.parseObject(content);
        JSONArray newsItem = jsonObject.getJSONArray("news_item");
        Iterator<Object> it = newsItem.iterator();
        while (it.hasNext()) {
            JSONObject item = (JSONObject) it.next();
            String title = item.getString("title");
            String thumbUrl = item.getString("thumb_url");
            String clickLink = item.getString("url");
            MaterialNewsItemVO itemVO = new MaterialNewsItemVO();
            itemVO.setTitle(title);
            itemVO.setClickLink(clickLink);
            itemVO.setTitleImg(adminProperties.getImgproxy() + thumbUrl);
            materialNewsVOs.add(itemVO);
        }
        return materialNewsVOs;
    }

    @Override
    public BaseResult saveWxMaterial(WxMaterialRequest request) {
        BaseResult result = wxMaterialService.saveWxMaterial(request);
        LOGGER.info("保存素材返回{}", result.isSuccess() ? "成功" : "失败");
        return result;
    }

    /**
     * 同步素材
     *
     * @param type
     * @return
     */
    @Override
    public Result<Boolean> syncMaterial(String appid, String type) {
        WxMaterialSyncRequest request = new WxMaterialSyncRequest();
        request.setType(type);
        request.setAppId(appid);
        BaseResult baseResult = wxMaterialService.syncMaterial(request);
        if (RpcResultCheckUtil.isSuccess(baseResult)) {
            return JsonResultBuilder.succ(true);
        }
        return JsonResultBuilder.fail(baseResult.getErrcode(), baseResult.getErrmsg());
    }

    @Override
    public WxMaterialDTO queryMaterialById(String mediaId) {
        SimpleResult<WxMaterialDTO> simpleResult = wxMaterialService.queryMaterialById(mediaId);
        if (simpleResult.isSuccess()) {
            return simpleResult.getData();
        }
        return null;
    }
}
